<template>
    <page-meta
        :page-style="'overflow:'+(state.showSex||state.showWork||state.showCity||state.showTime||state.showPick?'hidden':'visible')"></page-meta>
    <view class="content">
        <view class="head-wrap">
            <image src="@/static/images/bg.jpg" mode="scaleToFill" class="bg" />
            <view class="head-wrap-info">
                <view class="head-wrap-info-content">
                    <view class="head-wrap-info-content-left">
                        <view class="head-wrap-info-content-left-name">即刻加入认证专区</view>
                        <view class="head-wrap-info-content-left-tip">完成认证审核就可以接单啦</view>
                    </view>
                    <view class="head-wrap-info-content-right">
                        <image src="@/static/images/index/settled_tip.png" mode="scaleToFill"
                            style="width: 100%;height: 100%;" />
                    </view>
                </view>
            </view>
        </view>
        <view class="main-info">
            <view class="main-info-wrap">
                <up-form labelPosition="top" :model="state.model" :rules="state.rules" ref="formRef">
                    <up-form-item borderBottom>
                        <view style="display: flex;align-items: center;justify-content: space-between;">
                            <text>头像</text>
                            <view style="width: 100rpx;height: 100rpx;border-radius: 50%;border: 1px solid #f2f2f2;">
                                <button class="avatar-btn" open-type="chooseAvatar" @chooseavatar="onChooseavatar"
                                    hover-class="button-hover">
                                    <image :src="state.model.info.avatar" mode="scaleToFill"
                                        style="width: 100%;height: 100%;" />
                                </button>
                            </view>
                        </view>
                    </up-form-item>
                    <up-form-item label="昵称" prop="info.nickName" borderBottom>
                        <input type="nickname" class="weui-input" :value="state.model.info.nickName" @blur="bindblur"
                            placeholder="请填写昵称" @input="bindinput" />
                    </up-form-item>
                    <up-form-item label="性别" prop="info.sex_text" borderBottom>
                        <up-input v-model="state.model.info.sex_text" disabled="true" disabledColor="#ffffff"
                            border="none" placeholder="请选择性别"></up-input>
                        <template #right>
                            <up-icon name="arrow-right" @click="state.showSex=true"></up-icon>
                        </template>
                    </up-form-item>
                    <up-form-item label="电话" prop="info.phone" borderBottom>
                        <up-input v-model="state.model.info.phone" disabledColor="#ffffff" border="none"
                            placeholder="请填写电话"></up-input>
                    </up-form-item>
                    <up-form-item label="工作类型" prop="info.workTypeText" :labelWidth="100" borderBottom>
                        <up-input v-model="state.model.info.workTypeText" disabled="true" disabledColor="#ffffff"
                            border="none" placeholder="请选择工作类型"></up-input>
                        <template #right>
                            <up-icon name="arrow-right" @click="state.showWork=true"></up-icon>
                        </template>
                    </up-form-item>
                    <up-form-item label="当前职位" prop="info.positionItemIdText" :labelWidth="100" borderBottom>
                        <up-input v-model="state.model.info.positionItemIdText" disabled="true" disabledColor="#ffffff"
                            border="none" placeholder="请选择职位"></up-input>
                        <template #right>
                            <up-icon name="arrow-right" @click="openSelectJob"></up-icon>
                        </template>
                    </up-form-item>
                    <up-form-item label="所在地区" prop="info.areaText" :labelWidth="100" borderBottom>
                        <up-input v-model="state.model.info.areaText" disabled="true" disabledColor="#ffffff"
                            border="none" placeholder="请选择所在地区"></up-input>
                        <template #right>
                            <up-icon name="arrow-right" @click="state.showCity=true"></up-icon>
                        </template>
                    </up-form-item>
                    <up-form-item label="参加工作时间" prop="info.workDate" :labelWidth="100" borderBottom>
                        <up-input v-model="state.model.info.workDate" disabled="true" disabledColor="#ffffff"
                            border="none" placeholder="请选择参加工作时间"></up-input>
                        <template #right>
                            <up-icon name="arrow-right"
                                @click="state.showPick=true;state.pickModel='date'; state.pick_key='workDate'"></up-icon>
                        </template>
                    </up-form-item>
                    <up-form-item label="可接受月薪" prop="info.monthlyPay" :labelWidth="100" borderBottom>
                        <up-input v-model="state.model.info.monthlyPay" disabledColor="#ffffff" border="none"
                            placeholder="请填写可接受月薪"></up-input>
                    </up-form-item>
                    <up-form-item label="可接受日薪" prop="info.dailyPay" :labelWidth="100" borderBottom>
                        <up-input v-model="state.model.info.dailyPay" disabledColor="#ffffff" border="none"
                            placeholder="请填写可接受日薪"></up-input>
                    </up-form-item>
                    <up-form-item label="工作时间" :labelWidth="100" borderBottom>
                        <up-radio-group v-model="state.model.info.wayType" placement="row">
                            <up-radio :customStyle="{marginBottom: '8px'}" v-for="(item, index) in state.radiolist"
                                :key="index" :label="item.name" :name="item.id">
                            </up-radio>
                        </up-radio-group>
                        <view style="display: flex;margin-top: 12rpx;">
                            <view @click="openPick('startTime')">
                                <input style="text-align: center;" disabled="true" disabledColor="#ffffff"
                                    v-model="state.model.info.startTime" border="none" placeholder="开始时间" />
                            </view>
                            <up-icon name="arrow-right"></up-icon>
                            <view @click="openPick('endTime')">
                                <input style="text-align: center;" disabled="true" disabledColor="#ffffff"
                                    v-model="state.model.info.endTime" border="none" placeholder="结束时间" />
                            </view>
                        </view>
                    </up-form-item>
                    <up-form-item label="个人简介" prop="info.content" :labelWidth="100">
                        <up-textarea v-model="state.model.info.content" placeholder="个人简介"></up-textarea>
                    </up-form-item>
                </up-form>
            </view>
            <view class="main-info-wrap" style="margin-top:32rpx">
                <view style="padding:24rpx 0;">
                    <view class="area" style="margin-bottom: 24rpx;">
                        <view class="line"></view>
                        <text class="text">工作经历</text>
                    </view>
                    <view>
                        <form-card v-for="(item,index) in state.model.info.blurbSee" :item="item"
                            :key="index"></form-card>
                    </view>
                    <view>
                        <up-button @click="toResumeWork">添加工作经历</up-button>
                    </view>
                </view>
                <view style="padding: 24rpx 0;">
                    <view class="area" style="margin-bottom: 24rpx;">
                        <view class="line"></view>
                        <text class="text">工作技能</text>
                    </view>
                    <up-form>
                        <up-form-item>
                            <up-input v-model="state.model.info.blurbSkill_text" disabled="true" disabledColor="#ffffff" border="none"
                                placeholder="请选择工作职位"></up-input>
                            <template #right>
                                <up-icon name="arrow-right" @click="toResumeSkill"></up-icon>
                            </template>
                        </up-form-item>
                    </up-form>
                </view>
            </view>
        </view>
        <u-city-select v-model="state.showCity" @city-change="cityChange"></u-city-select>

        <up-datetime-picker ref="datetimePickerRef" :show="state.showPick" v-model="pickvalue" :mode="state.pickModel"
            :formatter="formatter" @confirm="onPickConfirm" @cancel="state.showPick=false"></up-datetime-picker>

        <up-action-sheet :show="state.showSex" :actions="state.sex_actions" title="请选择性别" cancelText="取消"
            @close="state.showSex=false" @select="sexSelect"></up-action-sheet>
        <up-action-sheet :show="state.showWork" :actions="state.work_actions" title="请选择工作类型" cancelText="取消"
            @close="state.showWork=false" @select="workSelect"></up-action-sheet>

        <view class="fixed-action-wrap">
            <view class="fixed-action-wrap-button" @click="submit">提交审核</view>
        </view>
    </view>
</template>
<script setup>
import { ref, reactive, getCurrentInstance, onMounted, onUnmounted } from "vue"
import { onReady } from "@dcloudio/uni-app"
// #ifdef MP-WEIXIN
const fs = uni.getFileSystemManager()
// #endif

const { proxy } = getCurrentInstance()
console.log(proxy)
const formRef = ref(null)
const datetimePickerRef = ref(null)
const state = reactive({
    model: {
        info: {
            avatar: "",
            nickName: "",
            sex: "",
            sex_text: "",
            phone: "",
            workType: "",
            workTypeText: "",
            positionItemId: "",
            positionItemIdText: "",
            areaText: "",
            proCode: "",
            cityCode: "",
            regionCode: "",
            workDate: "",
            wayType: "",
            startTime: "",
            endTime: "",
            blurbSee: [],
            blurbSkill: [],
            blurbSkill_text: "",
            monthlyPay: 0, // 月薪
            dailyPay: 0, // 日薪
            content: "", // 简介
        }
    },
    sex_actions: [
        { name: '男', id: 1 },
        { name: '女', id: 2 }
    ],
    work_actions: [
        { name: '兼职', id: 2 },
        { name: '全职', id: 1 }
    ],
    job_actions: [],
    radiolist: [
        {
            name: '工作日',
            id: 1,
            disabled: false,
        },
        {
            name: '周末',
            id: 2,
            disabled: false,
        }
    ],
    showSex: false,
    showWork: false,
    showCity: false,
    showTime: false,
    showPick: false,
    pick_key: "",
    pickModel: "date",
    pickvalue: Date.now(),
    rules: {
        'info.nickName': {
            type: 'string',
            required: true,
            message: '请填写昵称',
            trigger: ['blur', 'change', 'click'],
        },
        'info.sex_text': {
            type: 'string',
            required: true,
            message: '请选择性别',
            trigger: ['blur', 'change', 'click'],
        },
        'info.phone': {
            type: 'string',
            required: true,
            message: '请填写电话',
            trigger: ['blur', 'change'],
        },
        'info.workTypeText': {
            type: 'string',
            required: true,
            message: '请选择工作类型',
            trigger: ['blur', 'change', 'click'],
        },
        'info.positionItemIdText': {
            type: 'string',
            required: true,
            message: '请选择职位',
            trigger: ['blur', 'change', 'click'],
        },
        'info.areaText': {
            type: 'string',
            required: true,
            message: '请选择所在地区',
            trigger: ['blur', 'change', 'click'],
        },
        'info.workDate': {
            type: 'string',
            required: true,
            message: '请选择参加工作时间',
            trigger: ['blur', 'change', 'click'],
        },
        'info.monthlyPay': {
            type: 'string',
            required: true,
            message: '请填写可接受月薪',
            trigger: ['blur', 'change'],
        },
        'info.dailyPay': {
            type: 'string',
            required: true,
            message: '请填写可接受日薪',
            trigger: ['blur', 'change'],
        },
        'info.content': {
            type: 'string',
            required: true,
            message: '请填写个人简介',
            trigger: ['blur', 'change'],
        },
    }
})
async function onChooseavatar(e) {
    const base = fs.readFileSync(e.detail.avatarUrl, 'base64', 0)
    const basePath = 'data:image/jpeg;base64,' + base

    const res = await proxy.request('/common/file/image', { image: basePath }, {
        method: 'POST'
    })

    console.log(res.data.data)
    state.model.info.avatar = res.data.data
}


function bindblur(e) {
    state.model.info.nickName = e.detail.value
    formRef.value.validateField('info.nickName');
}

function bindinput(e) {
    state.model.info.nickName = e.detail.value
    formRef.value.validateField('info.nickName');
}
function onWorkSelect(e) {
    state.model.info.blurbSee.push(e)
    console.log(state.model.info.blurbSee)
}

function sexSelect(e) {
    state.model.info.sex = e.id
    state.model.info.sex_text = e.name
    formRef.value.validateField('info.sex_text');
}
function workSelect(e) {
    console.log(e)
    state.model.info.workType = e.id;
    state.model.info.workTypeText = e.name
    formRef.value.validateField('info.workTypeText');
}
function cityChange(e) {
    const { province, city, area } = e
    state.model.info.areaText = province.label + '-' + city.label + '-' + area.label;
    state.model.info.proCode = province.value + "0000"
    state.model.info.cityCode = city.value + "00"
    state.model.info.regionCode = area.value
    formRef.value.validateField('info.areaText');
}
function openSelectJob() {
    proxy.on('on-job-select', onJobSelect);
    let path = "/pages/mine/resume-job"
    toPage(path)
}

function onJobSelect(e) {
    console.log(e)
    state.model.info.positionItemId = e.id
    state.model.info.positionItemIdText = e.label
    formRef.value.validateField('info.positionItemIdText');
}
function onPickConfirm(e) {
    state.showPick = false
    if (state.pick_key == 'workDate') {
        let date = new Date(e.value);
        state.model.info[state.pick_key] = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
        formRef.value.validateField('info.workDate');
    } else {
        state.model.info[state.pick_key] = e.value
        formRef.value.validateField(`info[${state.pick_key}]`);
    }
}
function openPick(key) {
    state.pickModel = 'time'
    state.pickvalue = '01:01'
    state.showPick = true
    state.pick_key = key
}
function toResumeWork() {
    proxy.on('on-work-add', onWorkSelect);
    let path = "/pages/mine/resume-work"
    toPage(path)
}

function onSkillSelect(e) {
    console.log(e, '返回了')
    state.model.info.blurbSkill = e
    state.model.info.blurbSkill_text = e.map(item => item.label).join(',')
}
function toResumeSkill() {
    proxy.on('on-skill-select', onSkillSelect);
    let path = "/pages/mine/resume-skill"
    toPage(path)
}
function toPage(url) {
    uni.navigateTo({ url })
}
const formatter = (type, value) => {
    if (type === 'year') {
        return `${value}年`;
    }
    if (type === 'month') {
        return `${value}月`;
    }
    if (type === 'day') {
        return `${value}日`;
    }
    return value;
};

function submit() {
    formRef.value?.validate().then(async (valid) => {
        if (valid) {
            if (!state.model.info.avatar) {
                uni.$u.toast('请上传头像')
                return
            }

            if (!state.model.info.blurbSee.length) {
                uni.$u.toast('请添加工作经历')
                return
            }
            if (!state.model.info.blurbSkill.length) {
                uni.$u.toast('选择工作技能')
                return
            }
            let params = {
                ...state.model.info,
                blurbSkill: state.model.info.blurbSkill.map(item => {
                    return {
                        skillItemId: item.id
                    }
                })
            }
            console.log(params)
            uni.showLoading()
            const res = await proxy.request('/blurb/save', params)
            if (res.code == 200) {
               setTimeout(() => {
                uni.$u.toast('提交成功，待审核')
                formRef.value?.resetFields()
                formRef.value?.clearValidate()
                state.model.info.blurbSkill = []
                state.model.info.blurbSkill_text = ""
                state.model.blurbSee = []
                uni.hideLoading()
                uni.navigateBack()
               }, 750);
                // uni.navigateBack()
            }
            console.log(res)
        } else {
            uni.$u.toast('请检查信息是否填写完整')
            console.log(state.model.info)
        }
    }).catch((err) => {
        // 处理验证错误  
        console.log(err)
        uni.$u.toast('请检查信息是否填写完整')
    });
}

onReady(() => {
    // 微信小程序需要用此写法
    datetimePickerRef.value.setFormatter(formatter);
});
onUnmounted(() => {
    proxy.off('on-skill-select', () => {

    });
    proxy.off('on-job-select', () => {

    });
    proxy.off('on-work-add', () => {

    });
})
</script>
<style lang="scss">
page {
    // padding: 32rpx;
    background-color: #F5F5F5;
}
</style>
<style lang="scss" scoped>
::v-deep .u-action-sheet__item-wrap {
    overflow: auto;
    max-height: 50vh;
}

.head-wrap {
    position: relative;

    .bg {
        width: 100%;
        margin-top: -88rpx;
    }

    &-info {
        position: absolute;
        top: 36rpx;
        left: 32rpx;
        right: 32rpx;

        &-content {
            display: flex;
            align-items: center;
            justify-content: space-between;
            height: 220rpx;

            &-left {
                &-name {
                    margin-bottom: 20rpx;
                    font-family: PingFang SC, PingFang SC;
                    font-weight: 600;
                    font-size: 48rpx;
                    color: #FFFFFF;
                    line-height: 56rpx;
                    text-align: left;
                    font-style: normal;
                    text-transform: none;
                }

                &-tip {
                    font-family: PingFang SC, PingFang SC;
                    font-weight: 400;
                    font-size: 28rpx;
                    color: #FFFFFF;
                    line-height: 33rpx;
                    text-align: left;
                    font-style: normal;
                    text-transform: none;
                }
            }

            &-right {
                width: 220rpx;
                height: 220rpx;
            }
        }
    }
}

.main-info {
    padding: 32rpx;
    padding-bottom: 200rpx;
    // margin-top: 32rpx;

    &-wrap {
        width: 100%;
        padding: 20rpx;
        background: #FFFFFF;
        box-sizing: border-box;
        border-radius: 12rpx 12rpx 12rpx 12rpx;
    }

    .area {
        display: flex;

        .line {
            width: 8rpx;
            height: 32rpx;
            background: #F2CB51;
            border-radius: 12rpx 12rpx 12rpx 12rpx;
        }

        .text {
            margin-left: 20rpx;
            width: 128rpx;
            height: 44rpx;
            font-family: PingFang SC, PingFang SC;
            font-weight: 500;
            font-size: 32rpx;
            color: #323232;
            line-height: 38rpx;
            text-align: left;
            font-style: normal;
            text-transform: none;
        }
    }

    .avatar-btn {
        width: 100%;
        height: 100%;
        padding: 0;
        background: transparent;
        border: none;
        outline: none;
        border-radius: 50%;
    }
}

.fixed-action-wrap {
    position: fixed;
    left: 0;
    bottom: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 128rpx;
    padding: 32rpx;
    background-color: #FFFFFF;
    padding-bottom: env(safe-area-inset-bottom);
    box-sizing: border-box;
    z-index: 99;

    &-button {
        display: flex;
        align-items: center;
        justify-content: center;
        width: calc(100% - 24px);
        height: 80rpx;
        background: #F2CB51;
        border-radius: 58rpx 58rpx 58rpx 58rpx;
    }
}
</style>